#include "historydialog.h"
#include "ui_historydialog.h"

//#include <QSqlTableModel>
#include <QtSql>

HistoryDialog::HistoryDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::HistoryDialog)
{
    ui->setupUi(this);

    this->setupDatabase();
    this->setupDates();
    this->setupGraph();
    this->setupData();
}

HistoryDialog::~HistoryDialog()
{
    delete ui;
}

void HistoryDialog::setupDatabase()
{
    /*
     *QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(QDir::home().absoluteFilePath("SerialTemper.db"));
    if(!db.open()){
        qDebug() << "Sql error: " << db.lastError().text();
    }
    QSqlTableModel *model = new QSqlTableModel(this, db);
    */
    QSqlTableModel *model = new QSqlTableModel(this, QSqlDatabase::database());
    model->setTable("history");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    model->setHeaderData(0, Qt::Horizontal, tr("DateTime"));
    model->setHeaderData(1, Qt::Horizontal, tr("Temperature"));

    ui->tableView->setItemDelegateForColumn(model->fieldIndex("datetime"), new DateFormatDelegate("dd.MM.yyyy HH:mm", this));

    ui->tableView->setModel(model);
}


void HistoryDialog::on_start_dateEdit_dateChanged(const QDate &date)
{
    ui->end_dateEdit->setMinimumDate(date);
    if(ui->plot->graphCount() > 0) this->setupData();
}

void HistoryDialog::setupGraph()
{
    ui->plot->addGraph();
    QChar ch(0x00B0);

    ui->plot->yAxis->setLabel(QString("temperature (%1C)").arg(ch));

    ui->plot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    ui->plot->xAxis->setDateTimeFormat("HH:mm\ndd.MM.yy");
    // set a fixed tick-step to one tick per month:
    ui->plot->xAxis->setAutoTickStep(true);
    //ui->plot->xAxis->setTickStep(60); // in seconds
    ui->plot->xAxis->setSubTickCount(3);
    // set a more compact font size for bottom and left axis tick labels:
    ui->plot->xAxis->setTickLabelFont(QFont(QFont().family(), 6));
    ui->plot->yAxis->setTickLabelFont(QFont(QFont().family(), 6));
    // make left and bottom axes transfer their ranges to right and top axes:
    connect(ui->plot->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->plot->xAxis2, SLOT(setRange(QCPRange)));
    connect(ui->plot->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->plot->yAxis2, SLOT(setRange(QCPRange)));



    ui->plot->setRangeDrag(Qt::Horizontal);
    ui->plot->setRangeZoom(Qt::Horizontal);
    ui->plot->setInteraction(QCustomPlot::iRangeZoom);
    ui->plot->replot();
}

void HistoryDialog::setupDates()
{
    QSqlQuery* query = new QSqlQuery();
    QDateTime start_date, end_date;
    if(!query->exec("SELECT MIN(`datetime`), MAX(`datetime`) FROM `history`")){
        qDebug() << "SQL Error: " << query->lastError().text();
    }
    if(!query->first()) return;
    start_date.setTime_t(query->value(0).toInt());
    end_date.setTime_t(query->value(1).toInt());
    ui->start_dateEdit->setMinimumDate(start_date.date());
    ui->start_dateEdit->setMaximumDate(end_date.date());
    ui->start_dateEdit->setDate(end_date.date());

    ui->end_dateEdit->setMinimumDate(end_date.date());
    ui->end_dateEdit->setMaximumDate(end_date.date());
}

void HistoryDialog::setupData()
{
    QSqlQuery* query = new QSqlQuery();
    QDateTime start_date, end_date;
    double min_temp, max_temp;

    if(!query->exec("SELECT MIN(`temp`), MAX(`temp`) FROM `history`")){
        qDebug() << "SQL Error: " << query->lastError().text();
    }
    if(!query->first()) return;

    min_temp = query->value(0).toDouble();
    max_temp = query->value(1).toDouble();

    ui->plot->yAxis->setRange(min_temp<0?min_temp:0, max_temp<50?max_temp:50);


    start_date.setDate(ui->start_dateEdit->date());
    end_date.setDate(ui->end_dateEdit->date().addDays(1));
    start_date.setTime(QTime(0,0,0));
    end_date.setTime(QTime(0,0,0));

    if(!query->exec(QString("SELECT `datetime`,`temp` FROM `history`"
                            " WHERE `datetime` > %1 AND `datetime` < %2")
                    .arg(start_date.toTime_t())
                    .arg(end_date.toTime_t())
                    )){
        qDebug() << "SQL Error: " << query->lastError().text();
    }
    //qDebug() << "Remove graphs count: " <<  ui->plot->clearGraphs();
    uint d_time = 0;
    while(query->next()){
        if(abs(d_time - query->value(0).toUInt()) > (qApp->property("check_interval").toInt()*(qApp->property("attempts").toInt()+1))){
            ui->plot->addGraph();
            QPen pen;
            pen.setColor(Qt::darkCyan);
            ui->plot->graph(ui->plot->graphCount()-1)->setLineStyle(QCPGraph::lsLine);
            ui->plot->graph(ui->plot->graphCount()-1)->setPen(pen);
        }
        d_time = query->value(0).toUInt();
        ui->plot->graph(ui->plot->graphCount()-1)->addData(d_time, query->value(1).toDouble());
    }
    //ui->plot->xAxis->setTickStep(start_date.daysTo(end_date)/24);
    ui->plot->xAxis->setRange(start_date.toTime_t(), end_date.toTime_t());

    ui->plot->replot();
}

void HistoryDialog::on_end_dateEdit_dateChanged(const QDate &date)
{
    Q_UNUSED(date);
     if(ui->plot->graphCount() > 0) this->setupData();
}
